package dsk.demo.product.controller.user;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import dsk.demo.common.utils.PageQuery;
import dsk.demo.common.utils.R;
import dsk.demo.product.entity.UserEntity;
import dsk.demo.product.service.UserService;
import dsk.demo.product.util.CacheUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 用户模块
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    private final CacheUtil cacheUtil;

    @GetMapping("/list")
    public R list(UserEntity ivo, PageQuery pageQuery) {
        IPage list = userService.getList(ivo, pageQuery);
        return R.ok(list);
    }

    @PostMapping("/login")
    public R login(@RequestBody UserEntity ivo) {
        // 登录
        // 邮箱 || 用户名  登录
        if (StrUtil.isBlank(ivo.getUsername())) {
            return R.error(90001,"Please enter username");
        }
        if (StrUtil.isBlank(ivo.getPassword())) {
            return R.error(90001,"Please enter password");
        }
        return userService.login(ivo);
    }

    /**
     * 注册
     * @param ivo
     * @return
     */
    @PostMapping("/register")
    public R register(@RequestBody UserEntity ivo) {
        if (StrUtil.isBlank(ivo.getEmail())) {
            return R.error(90001,"Please enter email");
        }
        if (StrUtil.isBlank(ivo.getEmailCode())) {
            return R.error(90001, "Please enter email code");
        }
        if (StrUtil.isBlank(ivo.getUsername())) {
            return R.error(90001,"Please enter username");
        }
        if (StrUtil.isBlank(ivo.getPassword())) {
            return R.error(90001,"Please enter password");
        }
        if (StrUtil.isBlank(ivo.getFirstName())) {
            return R.error(90001,"Please enter firstName");
        }
        if (StrUtil.isBlank(ivo.getLastName())) {
            return R.error(90001,"Please enter lastName");
        }
        if (ivo.getPassword().length() < 8) {
            return R.error(90001,"Password must be at least 8 characters long");
        }
        // 邮箱验证码校验
        String value = cacheUtil.getValue("email:code:" + ivo.getEmail());
        if (StrUtil.compare(ivo.getEmailCode(), value, true) != 0) {
            return R.error(90001,"The email verification code is incorrect");
        }
        userService.saveUser(ivo);
        return R.ok();
    }
}
